package com.appcenter.application.service;

import com.appcenter.application.config.RemoteProperties;
import com.appcenter.application.dto.apps.AppDto;
import com.appcenter.application.dto.externalapi.BusinessSystemJobDto;
import com.appcenter.application.dto.jobs.ResultJobDto;
import com.appcenter.application.dto.menu.MenuDto;
import com.appcenter.application.dto.orgs.OrgDto;
import com.appcenter.application.dto.orgusers.ResultOrgUserDto;
import com.appcenter.application.dto.permissions.PermissionsDto;
import com.appcenter.application.dto.roles.RoleDto;
import com.appcenter.application.dto.users.UserApiDto;
import com.appcenter.application.expand.ObjectFinal;
import com.appcenter.application.expand.RedisUtil;
import com.appcenter.application.input.Job.GetResultJobInput;
import com.appcenter.application.input.Job.GetResultJobsInput;
import com.appcenter.application.input.app.GetAppsInput;
import com.appcenter.application.input.assortcode.AddAssortCodeInput;
import com.appcenter.application.input.assortcode.GetAssortCodeInput;
import com.appcenter.application.input.externalapi.*;
import com.appcenter.application.input.jobUser.GetJobUserInput;
import com.appcenter.application.input.orguser.GetOrgUsersInput;
import com.appcenter.application.input.permission.GetPermissionsServiceInput;
import com.appcenter.application.mapper.*;
import com.appcenter.application.model.*;
import com.appcenter.application.output.Job.GetResultJobOutput;
import com.appcenter.application.output.Job.GetResultJobsOutput;
import com.appcenter.application.output.app.GetAppsOutput;
import com.appcenter.application.output.assortcode.AddAssortCodeOutput;
import com.appcenter.application.output.assortcode.GetAssortCodeOutput;
import com.appcenter.application.output.externalapi.*;
import com.appcenter.application.output.orguser.GetOrgUsersOutput;
import com.appcenter.application.output.permission.GetPermissionsServiceOutput;
import com.appcenter.jz.Logger.BusinessLogger;
import com.appcenter.jz.Logger.LoggerGenre;
import com.appcenter.jz.app.CurrentUser;
import com.appcenter.jz.config.ErrorJsonResult;
import com.appcenter.jz.page.PagedResult;
import com.appcenter.jz.unit.ListUtils;
import com.appcenter.jz.unit.ObjectUnit;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.*;

import static org.apache.http.util.TextUtils.isBlank;
import static org.apache.logging.log4j.util.Strings.isNotBlank;

@EnableConfigurationProperties(RemoteProperties.class)
@Service
public class ExternalAPISercive {
    @Autowired
    UsersMapper usersMapper;
    @Autowired
    UserService userService;
    @Autowired
    DataMarkService dataMarkService;
    @Autowired
    RolesMapper rolesMapper;
    @Autowired
    PermissionsMapper permissionsMapper;
    @Autowired
    AssortCodeService assortCodeService;
    @Autowired
    ObjectFinal objectFinal;
    @Autowired
    RemoteProperties remoteProperties;
    @Autowired
    private HttpAPIService httpAPIService;
    @Autowired
    AssortCodesMapper assortCodesMapper;
    @Autowired
    ObjectMapper objectMapper;
    @Autowired
    OrgsMapper orgsMapper;
    @Autowired
    OrgUsersMapper orgUsersMapper;
    @Autowired
    OrgService orgService;

    @Autowired
    OrgUserService orgUserService;

    @Autowired
    JobsMapper jobsMapper;

    @Autowired
    OrgJobsMapper orgJobsMapper;
    @Autowired
    JobUsersMapper jobUsersMapper;
    @Autowired
    PermissionService permissionService;
    @Autowired
    AppsMapper appMapper;

    @Autowired
    RedisUtil redisUtil;


    /**
     *  创建人:Coke
     *  备注: 根据部门取人员
     *  时间: 2019/4/26 13:44
     *  参数:
     */
//    @Cacheable(value="basedata",keyGenerator = "ObjectKey")
    public GetOrgUsersOutput GetOrgUsers(GetOrgUsersInput input) throws Exception {
        input.setAppCode("JZ");
        return orgUserService.GetOrgUsers(input);
    }

    /**
     *  创建人:Coke
     *  备注: 获取人员信息
     *  时间: 2019/4/26 13:45
     *  参数:
     */
//    @Cacheable(value="basedata",keyGenerator = "ObjectKey")
    public GetUsersDetaileOutput GetUserDetaile(GetUsersDetaileInput input) throws Exception {
        GetUsersDetaileOutput output = new GetUsersDetaileOutput();

//        if (!isBlank(input.getOrgId()) && !isBlank(input.getJobId())) {
//
//        }

        List <GetUsersDetaileOutput.User> curUsers = new ArrayList <GetUsersDetaileOutput.User>();
        GetJobUserInput jobUserInput = new GetJobUserInput();
        jobUserInput.setAppCode(objectFinal.APP_CODE);
        jobUserInput.setJobId(input.getJobId());
        jobUserInput.setOrgId(input.getOrgId());
        jobUserInput.setKeyword(input.getKeyword());
        jobUserInput.setVersionNo(objectFinal.getDataEffectiveVersion());
        PageHelper.startPage(input.getPage().getPageNo(), input.getPage().getPageSize(), "UserName desc");
        curUsers = usersMapper.getsUsersByJobId(jobUserInput);
        for (GetUsersDetaileOutput.User user:curUsers)
        {
            user.setKey(user.getId());
            user.setValue(user.getId());
            user.setTitle(user.getUserName());
        }
        PageInfo <GetUsersDetaileOutput.User> page = new PageInfo <>(curUsers);
        output.setItems(new PagedResult <GetUsersDetaileOutput.User>(page.getList(), (int) page.getTotal()));






//        if (input.getGenre().equals("部门") || input.getGenre().equals("单位")) {
//            GetOrgUsersInput orgInput = new GetOrgUsersInput();
//            orgInput.setAppCode(objectFinal.APP_CODE);
//            orgInput.setPenetrate(false);
//            orgInput.setOrgId(input.getOrgId());
//            orgInput.setPage(input.getPage());
//            orgInput.setKeyword(input.getKeyword());
//            GetOrgUsersOutput orgOutput = orgUserService.GetOrgUsers(orgInput);
//            List <ResultOrgUserDto> items = orgOutput.getItems().getItems();
//            if (items != null && items.size() > 0) {
//
//                List <GetUsersDetaileOutput.User> curUsers = new ArrayList <GetUsersDetaileOutput.User>();
//                for (int i = 0; i < items.size(); i++) {
//                    GetUsersDetaileOutput.User curUser = new GetUsersDetaileOutput.User();
//                    curUser.setKey(items.get(i).getId());
//                    curUser.setValue(items.get(i).getId());
//                    curUser.setTitle(items.get(i).getUserName());
//
//                    curUser.setUserName(items.get(i).getUserName());
//                    curUser.setUserCode(items.get(i).getUserCode());
//                    curUser.setEmail(items.get(i).getEmail());
//                    curUser.setJobName("");
//                    curUser.setOfficePhone(items.get(i).getOfficePhone());
//                    curUser.setPhone(items.get(i).getPhone());
//                    curUser.setId(items.get(i).getId());
//                    curUser.setOrgName(items.get(i).getOrgName());
//                    curUsers.add(curUser);
//                }
//                output.setItems(new PagedResult <GetUsersDetaileOutput.User>(curUsers, (int) orgOutput.getItems().getTotalCount()));
//            }
//        } else {
//            // List<Users> ls=new ArrayList<Users>();
//
//        }
        return output;
    }

    //获取全部部门信息



    /**
     *  创建人:Coke
     *  备注: 获取全部部门
     *  时间: 2019/4/26 13:45
     *  参数:
     */
//    @Cacheable(value="basedata",keyGenerator = "ObjectKey")
    public GetOrgsOutput GetOrgs(GetOrgsInput input) throws Exception {
        GetOrgsOutput output = new GetOrgsOutput();
        Long curversion = objectFinal.getDataEffectiveVersion();
        List<OrgDto> ls= new ArrayList<OrgDto>();
        List<Orgs> orgs=orgService.getOrgs(input.getParentId(), "JZ", false, curversion, input.getJobShow());
        if(!input.getTile()){
            output.setOrgs(orgService.GetOrgTreeList(orgs));
        }else{
            for (int i = 0; i < orgs.size(); i++) {
                OrgDto orgDto=new OrgDto();
                BeanUtils.copyProperties(orgs.get(i), orgDto);
                ls.add(orgDto);
            }
            output.setOrgs(ls);
        }
        return output;
    }

    /**
     *  创建人:Coke
     *  备注: 获取单个部门信息
     *  时间: 2019/4/26 13:45
     *  参数:
     */
   // @Cacheable(value="basedata",keyGenerator = "ObjectKey")
    public GetOrgOutput GetOrg(GetOrgInput input) throws Exception {
        GetOrgOutput output = new GetOrgOutput();
        Long curversion = objectFinal.getDataEffectiveVersion();
        Example orgExample = new Example(Orgs.class);
        Example.Criteria orgCriteria = orgExample.createCriteria();
        orgCriteria.andEqualTo("id", input.getOrgId());
        orgCriteria.andEqualTo("versionNo", curversion);
        orgCriteria.andEqualTo("validStatus", true);
        Orgs curOrg = orgsMapper.selectOneByExample(orgExample);
        if (curOrg!=null) {
            List <Orgs> orgs = orgService.getOrgs(curOrg.getParentId(), "JZ", false, curversion, false);
            List <OrgDto> orgDtos = orgService.GetOrgTreeList(orgs);
            if (orgDtos != null && orgDtos.size() > 0) {
                output.setOrg(orgDtos.get(0));
            } else {
                output.setOrg(null);
            }
        }
        return output;
    }

    //完成
    /**
     *  创建人:Coke
     *  备注: 获取岗位信息
     *  时间: 2019/4/26 13:45
     *  参数:
     */
//    @Cacheable(value="basedata",keyGenerator = "ObjectKey")
    public GetResultJobsOutput GetJobs(GetResultJobsInput input) throws Exception {
        GetResultJobsOutput output = new GetResultJobsOutput();
        if (isNotBlank(input.getAppCode())) {
            List <ResultJobDto> ls = jobsMapper.GetJobsAPI(input.getAppCode(), input.getOrgCode(), input.getJobCode(), objectFinal.getDataEffectiveVersion());
            output.setJobs(ls);
        }

        return output;
    }

    //完成
    /**
     *  创建人:Coke
     *  备注: 获取单个岗位信息
     *  时间: 2019/4/26 13:45
     *  参数:
     */
//    @Cacheable(value="basedata",keyGenerator = "ObjectKey")
    public GetResultJobOutput GetJob(GetResultJobInput input) throws Exception {

        GetResultJobOutput output = new GetResultJobOutput();
        if (isNotBlank(input.getAppCode()) && isNotBlank(input.getJobCode())) {
            List <ResultJobDto> ls = jobsMapper.GetJobsAPI(input.getAppCode(), input.getOrgCode(), input.getJobCode(), objectFinal.getDataEffectiveVersion());
            if (ls != null && ls.size() > 0) {
                output.setJob(ls.get(0));
            }
        }
        return output;
    }

    //已完成
    /**
     *  创建人:Coke
     *  备注: 获取全部人员信息
     *  时间: 2019/4/26 13:46
     *  参数:
     */
//    @Cacheable(value="basedata",keyGenerator = "ObjectKey")
    public GetUsersOutput GetUsers(GetUsersInput input) throws Exception {
        GetUsersOutput output = new GetUsersOutput();
        if (isBlank(input.getAppCode())) {
            throw new ErrorJsonResult("1000031", "应用编号不能为空！");
        }
        Long curversion = objectFinal.getDataEffectiveVersion();
        output.setUsers(usersMapper.GetUsersAPI(input.getAppCode(), input.getOrgCdoe(), input.getRoleCode(), input.getJobCode(), "", curversion));
        return output;
    }


    //已完成
    /**
     *  创建人:Coke
     *  备注:获取单个人员信息
     *  时间: 2019/4/26 13:46
     *  参数:
     */
//    @Cacheable(value="basedata",keyGenerator = "ObjectKey")
    public GetUserOutput GetUser(GetUserInput input) throws Exception {
        GetUserOutput output = new GetUserOutput();
        if (isBlank(input.getAppCode())) {
            throw new ErrorJsonResult("1000031", "应用编号不能为空！");
        }
        Long curversion = objectFinal.getDataEffectiveVersion();
        List <UserApiDto> curList = usersMapper.GetUsersAPI(input.getAppCode(), "", "", "", input.getUserCode(), curversion);
        if (curList != null && curList.size() > 0) {
            output.setUser(curList.get(0));
        }
        return output;
    }

    /**
     *  创建人:Coke
     *  备注: 获取用户邮箱
     *  时间: 2019/4/26 13:46
     *  参数:
     */
    public GetUserEmailOutput GetUserEmailPassword(GetUserEmailInput input) throws Exception {
        GetUserEmailOutput output = new GetUserEmailOutput();
        if (isBlank(input.getUserCode())) {
            throw new ErrorJsonResult("1000031", "用户code不能为空！");
        }
        Long curversion = objectFinal.getDataEffectiveVersion();
        Users user  = usersMapper.getUsersByUserCode(input.getUserCode(),curversion);
        if (user!=null) {
            output.setUserCode(user.getUserCode());
            output.setEmail(user.getEmail());
            output.setEmailPassword(user.getEmailPassword());
        }
        return output;
    }

    /**
     *  创建人:Coke
     *  备注: 查询同步数据标志位
     *  时间: 2019/4/26 13:46
     *  参数:
     */
    public GetDataMarkOutput GetDataMark(GetDataMarkInput input) throws Exception {
        GetDataMarkOutput output = new GetDataMarkOutput();
        BeanUtils.copyProperties(dataMarkService.GetOperatDataMark(input.getGenre()), output);
        return output;
    }


    //已完成
    /**
     *  创建人:Coke
     *  备注: 查询角色信息
     *  时间: 2019/4/26 13:47 
     *  参数: 
     */
    public GetRolesOutput GetRoles(GetRolesInput input) throws Exception {
        GetRolesOutput output = new GetRolesOutput();
        if (isBlank(input.getAppCode())) {
            throw new ErrorJsonResult("1000031", "应用编号不能为空！");
        }
        output.setRoles(rolesMapper.GetRolesAPI(input.getAppCode()));
        return output;
    }

    //已完成
    /**
     *  创建人:Coke
     *  备注: 查询权限信息
     *  时间: 2019/4/26 13:47 
     *  参数: 
     */
    public GetPermissionsOutput GetPermissions(GetPermissionsInput input) throws Exception {
        GetPermissionsOutput output = new GetPermissionsOutput();
        if (isBlank(input.getAppCode())) {
            throw new ErrorJsonResult("1000031", "应用编号不能为空！");
        }
        output.setPermissions(permissionsMapper.GetPermissionsAPI(input.getAppCode()));
        return output;
    }

    //完成
    /**
     *  创建人:Coke
     *  备注: 查询授权信息
     *  时间: 2019/4/26 13:47 
     *  参数: 
     */
    public GetWarrantOutput GetWarrant(GetWarrantInput input) throws Exception {
        GetWarrantOutput output = new GetWarrantOutput();
        GetPermissionsServiceOutput ps = permissionService.GetPermissionsByCoke(input);
        output.setAppsPermissions(ps.getAppsPermissions());
        output.setMenuPermissions(ps.getMenuPermissions());
        return output;
    }

    //完成
    /**
     *  创建人:Coke
     *  备注: 查询菜单信息
     *  时间: 2019/4/26 13:47 
     *  参数: 
     */
    public GetMenusOutput GetMenus(GetMenusInput input) throws Exception {
        GetMenusOutput output = new GetMenusOutput();
        GetPermissionsServiceInput permissionsServiceInput = new GetPermissionsServiceInput();
        permissionsServiceInput.setAppCode(input.getAppCode());
        permissionsServiceInput.setUserCode(input.getUserCode());
        List <PermissionsDto> permissions = permissionService.GetPermissionsByCoke(permissionsServiceInput).getMenuPermissions();
        List <MenuDto> menus = new ArrayList <>();
        ls(permissions, menus);
        menus.sort((o1, o2) -> {
            if (o1.getLevel() > o2.getLevel()) {
                return 1;
            } else if (o1.getLevel() < o2.getLevel()) {
                return -1;
            } else {
                if (o1.getSort() == null) {
                    return 1;
                }
                if (o2.getSort() == null) {
                    return -1;
                }
                if (o1.getSort() > o2.getSort()) {
                    return 1;
                } else if (o1.getSort() == o2.getSort()) {
                    return 0;

                } else {
                    return -1;
                }
            }


        });
        Map <String, MenuDto> parentMenuDtoDic = new HashMap <String, MenuDto>();
        List <MenuDto> menuDtos = new ArrayList <MenuDto>();
        if (menus != null && menus.size() > 0) {
            for (int i = 0; i < menus.size(); i++) {
                MenuDto menuDto = new MenuDto();
                BeanUtils.copyProperties(menus.get(i), menuDto);
                if (menus.get(i).getParentId() == null || !parentMenuDtoDic.containsKey(menus.get(i).getParentId())) {
                    menuDtos.add(menuDto);
                } else {
                    MenuDto parentMenuDto = parentMenuDtoDic.get(menuDto.getParentId());
                    if (parentMenuDto.getChildren() == null) {
                        parentMenuDto.setChildren(new ArrayList <MenuDto>());
                    }
                    parentMenuDto.getChildren().add(menuDto);
                }
                parentMenuDtoDic.put(menuDto.getId(), menuDto);
            }
        }
        output.setMenus(menuDtos);
        return output;
    }

    private void ls(List <PermissionsDto> permissions, List <MenuDto> menus) {
        if (permissions != null && permissions.size() > 0) {
            for (PermissionsDto permissionsDto : permissions) {
                if (permissionsDto.getPermissionType().equals("菜单")) {
                    MenuDto menu = new MenuDto();
                    menu.setId(permissionsDto.getId());
                    menu.setKey(permissionsDto.getPermissionCode());
                    menu.setName(permissionsDto.getPermissionName());
                    menu.setUrl(permissionsDto.getUrl());
                    menu.setParentId(permissionsDto.getParentId());
                    menu.setIcon(permissionsDto.getIcon());
                    menu.setLevel(permissionsDto.getLevel());
                    menu.setSort(permissionsDto.getListOrder());
                    menus.add(menu);
                    if (permissionsDto.getChildren() != null && permissionsDto.getChildren().size() > 0) {
                        ls(permissionsDto.getChildren(), menus);
                    }
                }
            }
        }

    }

    /**
     *  创建人:Coke
     *  备注: 查询字典信息
     *  时间: 2019/4/26 13:47 
     *  参数: 
     */
   /* public GetDicsOutput GetDics(GetDicsInput input) throws Exception {
        GetDicsOutput output = new GetDicsOutput();
        return output;
    }*/


    /**
     *  创建人:Coke
     *  备注: 忘记密码分配验证码信息
     *  时间: 2019/4/26 13:48 
     *  参数: 
     */
    public AssignVerificationCodeOutput AssignVerificationCode(AssignVerificationCodeInput input) throws Exception {
        AssignVerificationCodeOutput output = new AssignVerificationCodeOutput();
        //先验证
        Example example = new Example(Users.class);
        Example.Criteria criteria = example.createCriteria();
       // criteria.andEqualTo("userCode", input.getUserCode()); 只根据手机号拿人员信息与钉钉信息；
        criteria.andEqualTo("phone", input.getPhone());
        criteria.andEqualTo("accountIsDisabled", false);
        criteria.andEqualTo("versionNo", objectFinal.getDataEffectiveVersion());
        List <Users> users = usersMapper.selectByExample(example);
        if (users != null && users.size() == 1) {
            if(users.get(0).getDingUserId()!=""&&users.get(0).getDingUserId()!=null) {
                //分配验证码
                AddAssortCodeInput addAssortCodeInput = new AddAssortCodeInput();
                addAssortCodeInput.setGenre("忘记密码");
                addAssortCodeInput.setUserCode(users.get(0).getUserCode());
                AddAssortCodeOutput addAssortCodeOutput = assortCodeService.AddAssortCode(addAssortCodeInput);
                //发送钉钉消息
                String GetAppsUrl = remoteProperties.getMsgUrl() + "/sendmsg";
                String responseJson = httpAPIService.JsonSMS(GetAppsUrl, "{\"msg\":{\"businessType\":\"忘记密码验证码\",\"createUserCode\":\"jim\",\"createUserId\":\"jim\",\"createUserName\":\"jim\",\"fromAppCode\":\"" + input.getAppCode() + "\",\"messageTypes\": [{\"msgType\": \"钉钉消息\"}],\"mobileUrl\":\"\",\"msContent\":\"您的验证码是:" + addAssortCodeOutput.getResult() + "\",\"pcUrl\":\"\",\"sendMessageTargets\":[{\"targetUserCode\":\"" + users.get(0).getDingUserId() + "\",\"targetUserName\":\"" + users.get(0).getUserName() + "\"}],\"title\":\"忘记密码-验证码\",\"toAppCode\":\"" + input.getAppCode() + "\"}}");
            }else
            {
                throw new ErrorJsonResult("10000031", "人员无钉钉号，请查证！");
            }
        } else {
            throw new ErrorJsonResult("10000031", "人员手机号存在问题，请查证！");
        }
        output.setResult("验证码发送成功");
        return output;
    }


    /**
     *  创建人:Coke
     *  备注: 修改用户密码
     *  时间: 2019/4/26 13:48 
     *  参数: 
     */
    public EditPassWordOutput EditPassWord(EditPassWordInput input) throws Exception {
        EditPassWordOutput output = new EditPassWordOutput();
        Example example = new Example(Users.class);
        Example.Criteria criteria = example.createCriteria();
        //criteria.andEqualTo("userCode", input.getUserCode());
        criteria.andEqualTo("phone", input.getPhone());
        criteria.andEqualTo("accountIsDisabled", false);
        criteria.andEqualTo("versionNo", objectFinal.getDataEffectiveVersion());
        List <Users> users = usersMapper.selectByExample(example);
        if (users != null && users.size() == 1) {
            GetAssortCodeInput getAssortCodeInput = new GetAssortCodeInput();
            getAssortCodeInput.setGenre("忘记密码");
            getAssortCodeInput.setUserCode(users.get(0).getUserCode());
            GetAssortCodeOutput getAssortCodeOutput = assortCodeService.GetAssortCode(getAssortCodeInput);
            if (input.getVerificationCode().equals(getAssortCodeOutput.getVerificationCode())) {
                //开始修改密码
                Users u = users.get(0);
                u.setPassword(input.getNewPassword());
                usersMapper.updateByPrimaryKey(u);
                //删除使用过的验证码
                assortCodesMapper.deleteByPrimaryKey(getAssortCodeOutput);
                output.setResultMsg("密码修改成功");
            }else{
                throw new ErrorJsonResult("10000031", "验证码错误");
            }

        } else {
            throw new ErrorJsonResult("10000031", "用户名与手机号不匹配");
        }

        return output;
    }
    /**
     *  创建人:WZL
     *  备注: 重置密码
     *  时间: 2019/5/23 13:48
     *  参数:
     */
    public EditPassWordOutput resetPassWord(ResetPasswordInput input) throws Exception{
        EditPassWordOutput output = new EditPassWordOutput();
        Example example = new Example(Users.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userCode",input.getUserCode());
        criteria.andEqualTo("versionNo", objectFinal.getDataEffectiveVersion());
        List <Users> users = usersMapper.selectByExample(example);
        if (users != null && users.size() == 1) {
                //开始修改密码
                Users u = users.get(0);
                u.setPassword(input.getNewPassWord());
                usersMapper.updateByPrimaryKey(u);
                output.setResultMsg("密码修改成功");


        } else {
            throw new ErrorJsonResult("10000031", "用户信息存在问题！");
        }

        return output;

    }

    /**
     *  创建人:Coke
     *  备注: 修改邮箱密码-分配验证码信息
     *  时间: 2019/4/26 13:48 
     *  参数: 
     */
    public AssignVerificationCodeOutput EmailAssignVerificationCode(AssignVerificationCodeInput input) throws Exception {
        AssignVerificationCodeOutput output = new AssignVerificationCodeOutput();
        //先验证
        Example example = new Example(Users.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userCode", input.getUserCode());
        // criteria.andEqualTo("phone", input.getPhone());
        criteria.andEqualTo("accountIsDisabled", false);
        criteria.andEqualTo("versionNo", objectFinal.getDataEffectiveVersion());
        List <Users> users = usersMapper.selectByExample(example);
        if (users != null && users.size() == 1) {
            if (isBlank(users.get(0).getDingUserId())) {
                throw new ErrorJsonResult("10000031", "未绑定钉钉账号，无法发送验证码，请联系管理员！");
            }
            //分配验证码
            AddAssortCodeInput addAssortCodeInput = new AddAssortCodeInput();
            addAssortCodeInput.setGenre("修改邮箱密码");
            addAssortCodeInput.setUserCode(input.getUserCode());
            AddAssortCodeOutput addAssortCodeOutput = assortCodeService.AddAssortCode(addAssortCodeInput);
            //发送钉钉消息
            String GetAppsUrl = remoteProperties.getMsgUrl() + "/sendmsg";
            String responseJson = httpAPIService.JsonSMS(GetAppsUrl, "{\"msg\":{\"businessType\":\"修改邮箱密码验证码\",\"createUserCode\":\"jim\",\"createUserId\":\"jim\",\"createUserName\":\"jim\",\"fromAppCode\":\"" + input.getAppCode() + "\",\"messageTypes\": [{\"msgType\": \"钉钉消息\"}],\"mobileUrl\":\"\",\"msContent\":\"您的验证码是:" + addAssortCodeOutput.getResult() + "\",\"pcUrl\":\"\",\"sendMessageTargets\":[{\"targetUserCode\":\"" + users.get(0).getDingUserId() + "\",\"targetUserName\":\"" + users.get(0).getUserName() + "\"}],\"title\":\"修改邮箱密码-验证码\",\"toAppCode\":\"" + input.getAppCode() + "\"}}");

        } else {
            throw new ErrorJsonResult("10000031", "该用户已被停用或不存在，请联系管理员！");
        }
        output.setResult("发送成功");
        return output;
    }

    /**
     *  创建人:Coke
     *  备注: /验证-验证码是否正确
     *  时间: 2019/4/26 13:48 
     *  参数: 
     */
    public VerificationVerificationCodeOutput VerificationVerificationCode(VerificationVerificationCodeInput input) throws Exception {
        VerificationVerificationCodeOutput output = new VerificationVerificationCodeOutput();
        GetAssortCodeOutput getAssortCodeOutput = assortCodeService.GetAssortCode(input);
        if (getAssortCodeOutput != null) {
            if (!input.getVerificationCode().equals(getAssortCodeOutput.getVerificationCode())) {
                throw new ErrorJsonResult("10000031", "验证码错误");
            }
        } else {
            throw new ErrorJsonResult("10000031", "验证码已过期，请重新发送验证码");
        }
        output.setResult("验证码正确");
        return output;
    }

    /**
     *  创建人:Coke
     *  备注: 修改邮箱密码
     *  时间: 2019/4/26 13:48 
     *  参数: 
     */
    public EditEmailPassWordOutput EditEmailPassWord(EditEmailPassWordInput input) throws Exception {
        EditEmailPassWordOutput output = new EditEmailPassWordOutput();
        Example example = new Example(Users.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userCode", input.getUserCode());
        criteria.andEqualTo("accountIsDisabled", false);
        criteria.andEqualTo("versionNo", objectFinal.getDataEffectiveVersion());
        List <Users> users = usersMapper.selectByExample(example);
        if (users != null && users.size() == 1) {

            if (input.getInIt()) {
                //开始修改密码
                Users u = users.get(0);
                u.setEmailPassword(input.getEmailPassWord());
                usersMapper.updateByPrimaryKey(u);
                output.setResult("邮箱密码修改成功");
            } else {
                GetAssortCodeInput getAssortCodeInput = new GetAssortCodeInput();
                getAssortCodeInput.setGenre("修改邮箱密码");
                getAssortCodeInput.setUserCode(input.getUserCode());
                GetAssortCodeOutput getAssortCodeOutput = assortCodeService.GetAssortCode(getAssortCodeInput);
                if (input.getVerificationCode().equals(getAssortCodeOutput.getVerificationCode())) {
                    //开始修改密码
                    Users u = users.get(0);
                    u.setEmailPassword(input.getEmailPassWord());
                    usersMapper.updateByPrimaryKey(u);

                    //删除使用过的验证码
                    assortCodesMapper.deleteByPrimaryKey(getAssortCodeOutput);
                    output.setResult("邮箱密码修改成功");
                } else {
                    throw new ErrorJsonResult("10000031", "验证码错误");
                }

            }


        } else {
            throw new ErrorJsonResult("10000031", "系统找不到此用户，请联系管理员");
        }

        return output;
    }

    //  public
    /**
     *  创建人:Coke
     *  备注: 根据岗位获取人员信息
     *  时间: 2019/4/26 13:48 
     *  参数: 
     */
//    @Cacheable(value="basedata",keyGenerator = "ObjectKey")
    public com.appcenter.application.output.user.GetUsersOutput GetJobUsers(com.appcenter.application.input.user.GetUsersInput input) throws Exception {
        input.setAppCode(objectFinal.APP_CODE);
        com.appcenter.application.output.user.GetUsersOutput output = userService.GetUsers(input);
        return output;
    }


    /**
     *  创建人:Coke
     *  备注: 业务系统获取用户信息
     *  时间: 2019/4/26 13:48 
     *  参数: 
     */
//    @Cacheable(value="basedata",keyGenerator = "ObjectKey")
    public GetBusinessSystemUsersOutput BusinessSystemUsers(BusinessSystemUsersInput input) throws Exception {
        GetBusinessSystemUsersOutput output = new GetBusinessSystemUsersOutput();
        Long curversion = objectFinal.getDataEffectiveVersion();
        output.setUsers(usersMapper.GetBusinessSystemUsersAPI("JZ", "", "", "", "", curversion));
        return output;
    }


    /**
     *  创建人:Coke
     *  备注: 业务系统获取全部岗位信息
     *  时间: 2019/4/26 13:48 
     *  参数: 
     */
//    @Cacheable(value="basedata",keyGenerator = "ObjectKey")
    public GetBusinessSystemJobsOutput BusinessSystemJobs(BusinessSystemJobsInput input) throws Exception {
        GetBusinessSystemJobsOutput output = new GetBusinessSystemJobsOutput();
        Long curversion = objectFinal.getDataEffectiveVersion();
        List <BusinessSystemJobDto> ls = jobsMapper.GetBusinessSystemJobs("JZ", null, null, curversion);
        output.setJobs(ls);
        return output;
    }

    /**
     *  创建人:Coke
     *  备注: 获取系统信息
     *  时间: 2019/4/26 14:02
     *  参数: 
     */
//    @Transactional
    public GetAppsOutput GetApps(GetAppsInput input) throws Exception {
        GetAppsOutput output = new GetAppsOutput();
        Example appExample = new Example(Apps.class);
        Example.Criteria criteriaKeyword = appExample.createCriteria();
        if (!isBlank(input.getKeyword())) {
            criteriaKeyword.orLike("appCode", "%" + input.getKeyword() + "%");
            criteriaKeyword.orLike("appName", "%" + input.getKeyword() + "%");
        }
        appExample.and(criteriaKeyword);
        Example.Criteria appCriteria = appExample.createCriteria();
        appCriteria.andEqualTo("validStatus", true);
        appCriteria.andIn("id", objectFinal.GetPermissionAppIds(ObjectFinal.APP_CODE, input.getUserCode()));
        appExample.and(appCriteria);


        PageHelper.startPage(input.getPage().getPageNo(), input.getPage().getPageSize(), "orderList");
        List <Apps> ls = appMapper.selectByExample(appExample);
        PageInfo <Apps> page = new PageInfo <>(ls);
        List <AppDto> newls = new ArrayList <AppDto>();
        for (int i = 0; i < ls.size(); i++) {
            AppDto appDto = new AppDto();
            BeanUtils.copyProperties(ls.get(i), appDto);
            newls.add(appDto);
        }
        BusinessLogger.Info(LoggerGenre.View, "获取应用", input);
        output.setItems(new PagedResult <AppDto>(newls, (int) page.getTotal()));
        return output;
    }

}
